package net.toocruel.iqismart.web.controller.common;

import net.toocruel.iqismart.dao.AreaRepository;
import net.toocruel.iqismart.security.core.support.Result;
import net.toocruel.iqismart.service.exception.BusinessException;
import net.toocruel.iqismart.utils.FileUploadUtils;
import net.toocruel.iqismart.web.controller.base.AbstractBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/6 上午4:38
 */
@Controller
@RequestMapping("image")
public class ImageController extends AbstractBaseController {
    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Value("${web.upload.path}")
    private String uploadPath;

    @RequestMapping("/avatar/{id}")
    public String sessionInvalid(@PathVariable Long id ,HttpServletRequest request, HttpServletResponse response){
        String avatarPath = fileUploadUtils.getAvatar(id);
        File file = new File(uploadPath + avatarPath);
        if(file.exists()){
            return "redirect:"+ avatarPath;
        }else{
            return "redirect:/static/images/default_avatar.jpg";
        }

    }


    @PostMapping("upload")
    @ResponseBody
    public Result upload(MultipartFile file,
                         HttpServletRequest request,
                         HttpServletResponse response,
                         HttpSession session,
                         RedirectAttributes redirectAttributes
    ) {
        String path = null;
        try {
            path = fileUploadUtils.upload(file.getInputStream(),file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }

        return  new Result(path);

    }



}
